package com.wskj.common.utils.file;

import cn.hutool.core.util.StrUtil;
import com.wskj.common.config.RuoYiConfig;
import com.wskj.common.constant.Constants;
import com.wskj.common.utils.common.AssertUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;

/**
 * 图片处理工具类
 *
 * @author ruoyi
 */
public class ImageUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath) {
        InputStream is = getFile(imagePath);
        try {
            AssertUtils.notNull(is, "空文件");
            return IOUtils.toByteArray(is);
        } catch (Exception e) {
            log.error("图片加载异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(String imagePath) {
        try {
            byte[] result = readFile(imagePath);
            Objects.requireNonNull(result);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        } catch (Exception e) {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url) {
        InputStream in = null;
        ByteArrayOutputStream baos = null;
        try {
            if (url.startsWith("http")) {
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            } else {
                // 本机地址
                String localPath = RuoYiConfig.getProfile();
                String downloadPath = localPath + StrUtil.subAfter(url, Constants.RESOURCE_PREFIX, false);
                in = new FileInputStream(downloadPath);
            }
            AssertUtils.notNull(in, "空文件");
            return IOUtils.toByteArray(in);
        } catch (Exception e) {
            log.error("获取文件路径异常 {}", e);
            return null;
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(baos);
        }
    }

    /**
     * 把网络图片转化为输入流
     *
     * @param imageUrl
     * @return
     * @throws Exception
     */
    public static InputStream getImageInputStream(String imageUrl) throws Exception {
        // 创建 URL 对象
        URL url = new URL(imageUrl);
        // 打开 HTTP 连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为 GET
        connection.setRequestMethod("GET");
        // 获取输入流
        return connection.getInputStream();
    }

    /**
     * 把输入流转换为字节数组
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] inputStreamToByteArray(InputStream inputStream) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;

        // 从输入流中不断读取数据并写入字节数组输出流
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }

        // 关闭流并返回字节数组
        return baos.toByteArray();
    }

    /**
     * 把字节数组转化base64字符串
     *
     * @param imageBytes
     * @return
     */
    public static String encodeToBase64(byte[] imageBytes) {
        // 使用 Base64 编码字节数组并返回字符串
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static byte[] addTextToImage(byte[] imageData, String realName,String inviteCode) throws IOException {

        // 小程序码图片
        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));


        // 加工后的图片
        BufferedImage image = new BufferedImage(500, 550, BufferedImage.TYPE_INT_RGB);

        //设置图片的背景色
        Graphics2D main = image.createGraphics();
        main.setColor(Color.white);
        main.fillRect(0, 0, 500, 550);

        //***********************插入中间广告图
        Graphics mainPic = image.getGraphics();

        mainPic.drawImage(originalImage, 40, 40, 400, 400, null);
        mainPic.dispose();

        //***********************页面头部
        Graphics titleG = image.createGraphics();
        //设置区域颜色
        //titleG.setColor(Color.white);
        //填充区域并确定区域大小位置
        //titleG.fillRect(450, 50, 450, 50);
        //设置字体颜色，先设置颜色，再填充内容
        titleG.setColor(Color.BLACK);
        //设置字体
        Font titleFont = new Font("SimSun", Font.BOLD, 30);
        titleG.setFont(titleFont);
        titleG.drawString(realName, 200, 500);
        titleG.drawString(inviteCode, 200, 530);


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();

        return imageInByte;
    }
}
